from datetime import datetime
from typing import Optional

from pydantic import BaseModel, Field, model_validator

# Removed Dify specific config import
# from configs import dify_config 
from core.entities.provider_entities import ProviderConfig
from core.plugin.entities.base import BasePluginEntity


class EndpointDeclaration(BaseModel):
    """
    declaration of an endpoint
    """

    path: str
    method: str
    hidden: bool = Field(default=False)


class EndpointProviderDeclaration(BaseModel):
    """
    declaration of an endpoint group
    """

    settings: list[ProviderConfig] = Field(default_factory=list)
    endpoints: Optional[list[EndpointDeclaration]] = Field(default_factory=list[EndpointDeclaration])


class EndpointEntity(BasePluginEntity):
    """
    entity of an endpoint
    """

    settings: dict
    tenant_id: str # This might need to be handled for a standalone service (e.g., fixed value or removed)
    plugin_id: str
    expired_at: datetime
    declaration: EndpointProviderDeclaration = Field(default_factory=EndpointProviderDeclaration)


class EndpointEntityWithInstance(EndpointEntity):
    name: str
    enabled: bool
    url: Optional[str] = None # Made optional as it might not always be present before validation
    hook_id: str

    @model_validator(mode="before")
    @classmethod
    def render_url_template(cls, values):
        # If a URL is already provided, use it. Otherwise, construct a simple one if hook_id is present.
        if "url" not in values or values["url"] is None:
            if "hook_id" in values and values["hook_id"]:
                # Simplified URL structure for standalone service, assuming a base path for plugins
                # This is a placeholder and might need adjustment based on actual frontend routing or deployment.
                values["url"] = f"/api/v1/plugins/endpoint/{values['hook_id']}"
            else:
                # If hook_id is not present, we cannot generate a URL. 
                # Depending on requirements, this could raise an error or leave url as None.
                pass # Keep url as None or handle as an error
        return values

